package com.tbit.common.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * 高德地图工具类
 *
 * @author <a href="mailto:chen.wutian@tbit.com.cn">BUGTian</a>
 * @since 2024/9/10
 */
@Slf4j
public class GDMapUtil {

    /**
     * 高德逆地理编码接口路径
     */
    private static final String RE_GEO_HOST = "https://restapi.amap.com/v3/geocode/regeo";

    /**
     * 返回结果字段名
     */
    private static final String STATUS_FIELD = "status";
    /**
     * 逆地理编码列表字段名
     */
    private static final String RE_GEOCODE_FIELD = "regeocode";
    /**
     * 地址描述字段名
     */
    private static final String FORMATTED_ADDRESS_FIELD = "formatted_address";
    /**
     * 返回结果状态值
     * 返回值为 0 或 1，0 表示请求失败；1 表示请求成功。
     */
    private static final String SUCCESS = "1";


    public static void main(String[] args) {
        System.out.println(getAddress(116.397128, 39.916527, "0c23c2156da265b11ee0afc4cf7ceaae"));
    }

    /**
     * 逆地理编码
     * @param lon 经度
     * @param lat 维度
     * @return 地址描述
     */
    public static String getAddress(Double lon, Double lat, String key) {
        String address = null;
        try {
            String body = HttpRequest.get(RE_GEO_HOST)
                    .form("location", String.format("%f,%f", lon, lat))
                    .form("key", key)
                    .timeout(5000)
                    .execute()
                    .body();
            JSONObject result = JSONObject.parseObject(body);
            if (SUCCESS.equals(result.get(STATUS_FIELD))) {
                address = result.getJSONObject(RE_GEOCODE_FIELD).getString(FORMATTED_ADDRESS_FIELD);
            } else {
                log.error("地址解析失败，API 返回内容：{}" ,body);
            }
        } catch (Exception e) {
            log.error("地址解析请求异常：{}" ,e.getMessage(), e);
        }
        log.info("坐标：[lon={}, lat={}]，解析地址：{}", lon, lat, address);
        return address;
    }
}
